<template>
  <div class="container">
    <el-form :model="form" label-width="auto" style="max-width: 600px" :inline="true">
      <el-form-item>
        <el-button type="primary" @click="toAdd">添加用户</el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchKeyword" placeholder="请输入用户名或姓名" clearable @clear="handleSearchClear">
          <template #append>
            <el-button icon="search" @click="handleSearch"/>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" width="180"/>
        <el-table-column prop="realName" label="真实姓名" width="180"/>
        <el-table-column prop="departmentId" label="部门ID" width="120"/>
        <el-table-column prop="userType" label="用户类型" width="120">
          <template #default="{row}">
            {{ formatUserType(row.userType) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.isDeleted === 1 ? 'success' : 'danger'">
              {{ row.isDeleted === 1 ? '已启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="toEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.isDeleted === 1 ? 'danger' : 'success'"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.isDeleted === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.isDeleted === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog 
      v-model="editDialogFormVisible" 
      :title="editForm.id ? '编辑用户' : '添加用户'" 
      width="500"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名" prop="username" required>
          <el-input v-model="editForm.username"/>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName" required>
          <el-input v-model="editForm.realName"/>
        </el-form-item>
        <el-form-item label="部门ID" prop="departmentId" required>
          <el-input v-model.number="editForm.departmentId" type="number"/>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType" required>
          <el-select v-model="editForm.userType" placeholder="请选择用户类型">
            <el-option label="管理员" :value="1"/>
            <el-option label="医生" :value="2"/>
            <el-option label="护士" :value="3"/>
            <el-option label="药剂师" :value="4"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!editForm.id" label="密码" prop="password" required>
          <el-input v-model="editForm.password" type="password"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="editDialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'

const form = ref({})
const editForm = ref({
  id: null,
  username: '',
  password: '',
  realName: '',
  departmentId: null,
  userType: 2, // 默认医生
  isDeleted: 1 // 1表示存在/启用
})
const editDialogFormVisible = ref(false)
const tableData = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 格式化用户类型
const formatUserType = (type) => {
  const types = {
    1: '管理员',
    2: '医生',
    3: '护士',
    4: '药剂师'
  }
  return types[type] || '未知'
}

// 获取列表数据
async function listData() {
  try {
    loading.value = true
    const data = await service.get("/user/list")
    tableData.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('Error:', error)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 搜索用户
async function handleSearch() {
  try {
    loading.value = true
    const data = await service.get("/user/search", {
      params: { keyword: searchKeyword.value }
    })
    tableData.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('搜索失败')
    console.error('Error:', error)
  } finally {
    loading.value = false
  }
}

// 清除搜索
function handleSearchClear() {
  searchKeyword.value = ''
  listData()
}

// 保存数据
async function save() {
  try {
    if (!editForm.value.username || !editForm.value.realName || 
        !editForm.value.departmentId ||
        (!editForm.value.id && !editForm.value.password)) {
      ElMessage.error('请填写完整信息')
      return
    }

    const apiUrl = editForm.value.id 
      ? `/user/update` 
      : `/user/add`
      
    const data = await service.post(apiUrl, editForm.value)
    
    ElNotification.success(editForm.value.id ? '更新成功' : '添加成功')
    editDialogFormVisible.value = false
    listData()
  } catch (error) {
    // 错误信息已经在拦截器中处理，这里不需要再处理
  }
}

// 切换状态
function toggleStatus(row) {
  ElMessageBox.confirm(
    `确认要${row.isDeleted === 1 ? '禁用' : '启用'}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await service.post(`/user/status`, {
        id: row.id,
        isDeleted: row.isDeleted === 1 ? 0 : 1
      })
      ElMessage.success('状态更新成功')
      listData()
    } catch (error) {
      // 错误信息已经在拦截器中处理
    }
  })
}

// 删除数据
function handleDelete(row) {
  ElMessageBox.confirm(
    '确认要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      await service.delete(`/user/delete/${row.id}`)
      ElMessage.success('删除成功')
      listData()
    } catch (error) {
      // 错误信息已经在拦截器中处理
    }
  })
}

function toAdd() {
  editForm.value = {
    id: null,
    username: '',
    password: '',
    realName: '',
    departmentId: null,
    userType: 2,
    isDeleted: 1
  }
  editDialogFormVisible.value = true
}

function toEdit(row) {
  editForm.value = { ...row }
  // 清空密码，编辑时不修改密码
  editForm.value.password = ''
  editDialogFormVisible.value = true
}

onMounted(() => {
  listData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>